package com.data.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.config.dao.EquStateConfigDao;
import com.config.dao.EquipmentDao;
import com.config.dao.LineConfigDao;
import com.config.entity.EquStateConfig;
import com.config.entity.Equipment;
import com.config.entity.LineConfig;
import com.data.dao.StateDayDao;
import com.data.dao.StateMinDao;
import com.data.entity.StateDay;
import com.data.entity.StateMin;

@Service("stateDayService")
public class StateDayServiceImpl implements StateDayService{
	@Resource(name="lineConfigDao")
	private LineConfigDao lineConfigDao;
	@Resource(name="equipmentDao")
	private EquipmentDao equipmentDao;
	@Resource(name="stateDayDao")
	private StateDayDao stateDayDao;
	@Resource(name="stateMinDao")
	private StateMinDao stateMinDao;
	@Resource(name="equStateConfigDao")
	private EquStateConfigDao equStateConfigDao;
	/**
	 * 根据时间提取每天设备状态数据
	 * @param belongDate
	 */
	@Override
	public void saveStateDay(Date belongDate) {
		try{
			SimpleDateFormat sdft = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			SimpleDateFormat sdt = new SimpleDateFormat("HH:mm:ss");
			List<EquStateConfig> states=equStateConfigDao.findAll();
			List<LineConfig> lines=lineConfigDao.findAllLine();
			if(lines.size()!=0){
				for(LineConfig line:lines){
					List<Equipment> equs=equipmentDao.listByLine(line.getId());
					if(equs.size()!=0){
						for(Equipment e:equs){
							if(states.size()!=0){
								for(EquStateConfig state:states){
									double duration=0.0; double relativeComp=0.0;
									StateDay day=stateDayDao.getStateDay(e.getId(), state.getStateType(), sdf.format(belongDate));
									 boolean isNew=false;
									 if(day==null){
										 day=new StateDay();
										 day.setEquId(e.getId());
										 day.setStateType(state.getStateType());
										 day.setBelongDate(sdf.parse(sdf.format(belongDate)));
										isNew=true;
									}	
									 String startDate=sdf.format(belongDate)+" "+"00:00:00";
									 List<StateMin> mins=stateMinDao.getStateMins(e.getId(), state.getStateType(), startDate, sdft.format(belongDate));
										if(mins.size()!=0){
											 for(StateMin min:mins){
												 duration+=min.getDuration();
												 relativeComp+=min.getRelativeComp();
											 }
										}
										day.setDuration(duration);
										day.setRelativeComp(relativeComp);
										if(isNew){
											stateDayDao.save(day);
										}else{
											stateDayDao.update(day);
										}
								}
							}
						}
				   }
				}
		    }
		 } catch (ParseException e1) {
	         e1.printStackTrace();
   }
  }
}
